package com.ququ.syb.mqhandler.service;

import com.ququ.common.utils.WorkingDayUtil;
import com.ququ.syb.common.constant.PayChannelClearTypeConstant;
import com.ququ.syb.common.constant.RabbitMqQueueNameConstant;
import com.ququ.syb.common.constant.WithdrawStatusConstant;
import com.ququ.syb.common.pojo.PayChannel;
import com.ququ.syb.common.pojo.WithdrawOrder;
import com.ququ.syb.mqhandler.fegin.PayChannelFegin;
import com.ququ.syb.mqhandler.fegin.WithdrawOrderFegin;
import com.ququ.syb.mqhandler.rabbitmq.RabbitMQSender;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class AuditWithdrawSuccessService {

    private Logger logger = LoggerFactory.getLogger(AuditWithdrawSuccessService.class);
    @Autowired
    private PayChannelFegin payChannelFegin;
    @Autowired
    private WithdrawOrderFegin withdrawOrderFegin;
    @Autowired
    private RabbitMQSender rabbitMQSender;

    public void withdrawProcess(String tradenum){
        WithdrawOrder withdrawOrder = withdrawOrderFegin.queryWithdrawOrder(tradenum).getData();
        if (withdrawOrder == null){
            logger.error("{}提现订单号不存在，不处理",tradenum);
            return;
        }
        if (withdrawOrder.getStatus() != WithdrawStatusConstant.AUDIT_SUCCESS){
            logger.error("{}提现订单状态为{}，不是审核完成状态，不能处理");
            return;
        }
        PayChannel payChannel = payChannelFegin.getPayChannel(withdrawOrder.getPaychannelid()).getData();
        String withdrawQueueName = payChannel.getIsAutoClear()==PayChannelClearTypeConstant.REAL_DIRECT_CLEAR?RabbitMqQueueNameConstant.WITHDRAW_VIRTUAL:payChannel.getWithdrawqueue();
        if (payChannel.getWithdrawstart() != null && payChannel.getWithdrawstop() != null){
            Date now = new Date();
            int hour = now.getHours();
            Date nextday = now;
            if (hour >= payChannel.getWithdrawstop()){
                nextday = WorkingDayUtil.getNextDay(now);
            }
            if (hour >= payChannel.getWithdrawstop() || hour < payChannel.getWithdrawstart()) {
                logger.debug("{}提现订单不在通道出款时间内，挂起延期处理",tradenum);
                nextday.setHours(payChannel.getWithdrawstart());
                nextday.setMinutes(5);
                rabbitMQSender.send(RabbitMqQueueNameConstant.T1_DELAY_WITHDRAW_SUCCESS_DEAD,tradenum,nextday.getTime()-now.getTime());
                return;
            }
        }
        rabbitMQSender.send(withdrawQueueName,tradenum);
    }
}
